package com.test.cordova.service;

import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.test.cordova.util.SharedPreferencesUtil;
import com.test.cordova.util.StorageUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2018/9/4 0004.
 */

public class InstallApkService extends IntentService {

    private static final String TAG = InstallApkService.class.getSimpleName();

    public InstallApkService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        readAssetsApk();
    }

    /**
     * 遍历assets 中apk 下安装包
     */
    private void readAssetsApk() {
        String[] files = null;
        try {
            // 遍历assest文件夹，读取压缩包及安装包
            files = getAssets().list("apk");
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i];
                Log.i(TAG, " fileName: " + fileName + " thread : " + Thread.currentThread().getName());
                if (fileName.contains(".apk")) {//判断是否为Apk
                    String apkName = fileName;
                    File externalCacheDir = StorageUtil.getCacheDirectory(this);//不能直接读取assets目录下的Apk信息，所以需要先将其拷贝出来
                    File apkFile = new File(externalCacheDir, apkName);
                    boolean isSuccess = copyFileFromAssets(apkName, apkFile);
                    if (isSuccess) {
                        installAPk(apkFile);
                    }
                }
            }
            SharedPreferencesUtil.putBoolean(this, "isTip",true);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制assets 文件到本地
     *
     * @param apkName
     * @param apkFile
     * @return
     */
    public boolean copyFileFromAssets(String apkName, File apkFile) {

        boolean flag = false;
        int BUFFER = 1024;
        OutputStream out = null;
        InputStream inputStream = null;
        byte buffer[] = null;

        try {
            inputStream = getAssets().open("apk/" + apkName);
            out = new FileOutputStream(apkFile);
            buffer = new byte[BUFFER];
            int byteread = 0;
            while ((byteread = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            flag = true;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 启动安装
     * @param apkFile
     */
    private void installAPk(File apkFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
        try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException ignored) {
        }
        Log.i(TAG, "Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT + " Build.VERSION_CODES.N:" + Build.VERSION_CODES.N + " apkFile:" + apkFile.getAbsolutePath());
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // TODO: 2018/9/4 0004  注意 第二个参数要 apk包名.provider 
            Uri contentUri = FileProvider.getUriForFile(this, "com.main_exit.cordova.provider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);

    }

}
